/* ERP价目表 */
<template>
  <div class="app-containers">
    <query-table-render
        ref="queryTable"
        :query-model="queryModel"
        :table-request="requestTableData"
        :table-column="tableColumns"
        :toolbar-render="toolbarRnd"
        :transform-query="transformQuery"
        :title-render="titleRender"
        @on-operator="onOperator"
    >
      <template v-slot:form>
        <el-form-item label="使用状态" prop="status">
          <el-select v-model="queryModel.status" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.price_use_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="客户方式" prop="mode">
          <el-select v-model="queryModel.mode" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.price_customer_mode"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="价目表名称" prop="priceName">
          <el-input v-model="queryModel.priceName" placeholder="请输入" clearable @keyup.enter.native="searchListQuery"/>
        </el-form-item>
        <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="queryModel.orderType" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.order_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="价目表别名" prop="priceAlias">
          <el-input v-model="queryModel.priceAlias" placeholder="请输入" clearable @keyup.enter.native="searchListQuery"/>
        </el-form-item>
        <el-form-item label="价目生效日期" prop="effectiveTimeRange" :autoAlign="true">
          <el-date-picker
              v-model="queryModel.effectiveTimeRange"
              type="daterange"
              format="yyyy/MM/dd"
              value-format="yyyy-MM-dd"
              range-separator="-"
              style="width:100%"
              start-placeholder="开始时间"
              end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="价目失效日期" prop="failureTimeRange" :autoAlign="true">
          <el-date-picker
              v-model="queryModel.failureTimeRange"
              type="daterange"
              format="yyyy/MM/dd"
              range-separator="-"
              style="width:100%"
              value-format="yyyy-MM-dd"
              start-placeholder="开始时间"
              end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="queryModel.orderType" style="width:100%" placeholder="请选择" clearable>
            <el-option
                v-for="item in dict.type.order_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item> -->
      </template>
    </query-table-render>

    <el-dialog title="配置可用价目表" :visible.sync="editVisible" width="720px" append-to-body :close-on-click-modal="false">
      <div class="dialog-main">
        <div class="dialog-left">
          <el-form :inline="true">
            <el-form-item label="价目表名称:">
              <el-input
                placeholder="请输入"
                clearable
                v-model="filterText"
                size="small"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="" style="margin-bottom: 0;">
              <div class="left-area">
                <el-tree
                  :data="settingPriceList"
                  show-checkbox
                  ref="menu"
                  node-key="id"
                  :check-strictly="false"
                  empty-text="暂无数据"
                  :props="defaultProps"
                  @node-click="nodeClick"
                  @check="treeCheck"
                  :filter-node-method="filterNodeArea"
                ></el-tree>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="dialog-right">
          <span class="right-top">已选价目表</span>
          <el-table
            class="right-bottom"
            :data="checkedSettingPrices" 
            :inline="true"
            :border="false"
          >
            <el-table-column label="" align="left" prop="name" width="340px">
              <template slot-scope="scope">
                <div class="table-column-area">
                  <span class="table-column-area-span">{{ scope.row.name }}</span>
                  <el-button class="table-column-area-btn" size="mini" type="text" icon="el-icon-circle-close" @click="deleteCanPrice(scope.row)"></el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="btnLoad">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="修改价目表" :visible.sync="orderTypeShow" width="478px" append-to-body :close-on-click-modal="false">
      <el-form ref="updateForm" class="page-search-wrap-form" :model="curRecord" size="small" :rules="rules" label-width="100px">
        <el-form-item label="对应订单类型:">
          <el-radio-group v-model="curRecord.orderType">
          <el-radio v-for="item in dict.type.order_type" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
        </el-form-item>
        <el-form-item label="别名:" prop="priceAlias">
          <el-input
            v-model="curRecord.priceAlias"
            placeholder="请输入别名"
            clearable
            size="small"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="排序编号:" prop="sort">
          <el-input-number v-model="curRecord.sort" controls-position="right" :min="1" style="width: 100%;" placeholder="请输入"></el-input-number>
          <!-- <template slot-scope="scope">
            <el-input
              placeholder="请输入"
              v-model="curRecord.sort"
              clearable
              maxlength="5"
              size="small"
              oninput="this.value= this.value.match(/\d+/) ? this.value.match(/\d+/)[0] : '';"
              @blur="scope.row.sort=$event.target.value"
            />
          </template> -->
        </el-form-item>
        <el-form-item label="业务人员:" prop="businessUserListStr">
          <el-input v-model="curRecord.businessUserListStr" :autosize="{ minRows: 5, maxRows: 5}" type="textarea" placeholder="请选择" disabled></el-input>
          <el-button type="primary" size="small" style="margin-top: 8px;" @click="onConfigPerson">配置人员</el-button>
        </el-form-item>
      </el-form>
      <!-- <div>
        
      </div> -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelOrderType">取 消</el-button>
        <el-button type="primary" @click="submitOrderTypeForm" :loading="btnOrderTypeLoad">确 定</el-button>
      </div>
    </el-dialog>
      

    <el-dialog title="配置业务人员" :visible.sync="configPersonShow" width="720px" append-to-body :close-on-click-modal="false">
      <div class="dialog-main">
        <div class="dialog-left">
          <el-form :inline="true">
            <el-form-item label="业务人员名称:">
              <el-input
                placeholder="请输入"
                clearable
                v-model="filterPersonText"
                size="small"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="" style="margin-bottom: 0;">
              <div class="left-area">
                <el-tree
                  :data="salesmans"
                  show-checkbox
                  ref="menuPerson"
                  node-key="userId"
                  :check-strictly="false"
                  empty-text="暂无数据"
                  :props="defaultPersonProps"
                  @node-click="nodeClickPerson"
                  @check="treeCheckPerson"
                  :filter-node-method="filterNodePerson"
                ></el-tree>
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="dialog-right">
          <span class="right-top">已选择的业务人员</span>
          <el-table
            class="right-bottom"
            :data="checkedConfigPersons" 
            :inline="true"
            :border="false"
          >
            <el-table-column label="" align="left" prop="name" width="340px">
              <template slot-scope="scope">
                <div class="table-column-area">
                  <span class="table-column-area-span">{{ scope.row.userDeptName }}</span>
                  <el-button class="table-column-area-btn" size="mini" type="text" icon="el-icon-circle-close" @click="deleteCanPricePerson(scope.row)"></el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelConfigPersonDialog">取 消</el-button>
        <el-button type="primary" @click="submitFormConfigPerson" :loading="btnLoad">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {checkPermi} from '@/utils/permission.js'
import QueryTableRender from "@/components/QueryTableRender";
import {settingPrices, settingPricePages, settingPricesUpdate, settingPriceStatus, getUserInfoList} from '@/api/basic/sellPrices.js'

// import {getOrderTerminalList} from "@/api/costManagement";
// import DialogCostEdit from "@/views/costManagement/components/DialogCostEdit";
import dayjs from "dayjs"

export default {
  name: "sellPrices",
  components: {QueryTableRender},
  dicts: ['basic_data_division', 'order_type', 'price_customer_mode', 'price_use_status'], // 可配置价目表
  data() {
    // const statusOptions = [{label: '启用', value:'1'}, {label: '禁用', value: '0'}]; // 使用状态
    // const customerModeOptions = [{label: '客户', value:'0'}, {label: '客户分类', value:'1'}]; // 客户方式
    // const orderTypeOptions = [{label: '普货', value: '0'}, {label: '买断', value: '1'}];// 订单类型
    // const todayStart = dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss')
    // const todayEnd = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
    return {
      // todayStart:todayStart,
      // todayEnd:todayEnd,
      btnLoad: false, // 点击确认按钮后 旋转轮
      btnOrderTypeLoad: false, // 修改订单类型确认按钮
      defaultProps: {
        children: "children",
        label: "name"
      },
      defaultPersonProps: {
        children: "children",
        label: "userDeptName"
      },
      orderTypeShow: false, // 是否显示修改订单类型弹窗
      configPersonShow: false, // 是否显示配置人员弹窗
      filterText: '', // 搜索价目表
      filterPersonText: '', // 搜索业务人员名称
      settingSourcePrices: [], // 所有可配置的价目表数据 原始数据
      settingPriceList: [], // 所有可配置的价目表数据
      checkedSettingPrices: [], // 可用的价目表数据
      checkedConfigPersons: [], // 已经选择的配置业务人员
      queryModel: {},
      // statusOptions: statusOptions, // 使用状态
      // customerModeOptions: customerModeOptions, // 客户方式
      // orderTypeOptions: orderTypeOptions, // 订单类型
      tableColumns: [],
      editVisible: false,
      curRecord: {}, // 当前记录
      customerValue: [], //  价目数据
      customerData: [],
      salesmans: [], // 业务人员列表
      rules: {
        priceAlias: [
        {required: true, message: "请输入别名", trigger: "blur"}
        ]
      },
    }
  },
  created() {
    this.setupQueryModel();
    this.setupTableColumns();
  },
  mounted() {
    // this.getSettingPrices();
  },
  watch: {
    filterText(val) { // 搜索价目表
      this.$refs.menu.filter(val);
    },
    filterPersonText(val) { // 搜索业务人员
      this.$refs.menuPerson.filter(val);
    }
  },
  methods: {

    setupQueryModel() {
      this.queryModel = {
        status: undefined, // 使用状态
        mode: undefined, // 适用客户方式
        priceName: undefined, // 价目表名称
        priceAlias: undefined, // 价目表别名
        effectiveTimeRange: undefined, // 生效日期 startOrderTime, endOrderTime
        effectiveDateBegin: undefined, // 生效日期 startOrderTime
        effectiveDateEnd: undefined, // 生效日期 endOrderTime
        failureTimeRange: undefined, // 失效日期 startOrderTime, endOrderTime
        expireDateBegin: undefined, // 失效日期 startOrderTime
        expireDateEnd: undefined, // 失效日期 endOrderTime
        orderType: undefined, // 订单类型
      };
    },

    setupTableColumns() {
      this.tableColumns = [
        {
          label: '序号',
          width: '60',
          type: 'index',
          increment: true
        },
        {
          prop: 'priceCode',
          label: '价目表编码',
          align: 'left',
          minWidth: '160',
          showOverflowTooltip: true
        },
        {
          prop: 'priceName',
          label: '价目表名称',
          align: 'left',
          minWidth: '180',
          showOverflowTooltip: true
        },
        {
          prop: 'priceAlias',
          label: '价目表别名',
          align: 'left',
          minWidth: '180',
          showOverflowTooltip: true
        },
        {
          prop: 'status',
          label: '使用状态',
          align: 'left',
          // type: 'select',
          minWidth: '120',
          render: (h, text) => {
            let show = "";
            this.dict.type.price_use_status.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
          // options: [
          //   {value: true, label: '启用', type: 'success'},
          //   {value: false, label: '禁用', type: 'danger'},
          // ],
          // render: (h,text, {selectOption}) => {
          //   return <el-tag type={selectOption.type}>{text}</el-tag>
          // }
        },
        {
          prop: 'mode',
          label: '适用客户方式',
          align: 'left',
          minWidth: '120',
          render: (h, text) => {
            let show = "";
            this.dict.type.price_customer_mode.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'customerInfo',
          label: '包含客户/客户分类',
          align: 'left',
          minWidth: '180',
          render:(h, text, {record}) => {
            let list = [];
            record.customerInfo && record.customerInfo.forEach((name) => {
              list.push(h('li', {style:'height: 22px; line-height: 22px; font-size: 14px; font-weight: 400;'}, name));
            });
            return h('el-tooltip', {props: {placement: 'top'}}, [
              h('div', {slot: 'content', style: 'min-width: 160px; max-height:236px; overflow: auto;'}, [
                h('ul', {style: 'list-style-type: none; padding-left:0;'}, list)
              ]),
              h('span', {style: 'overflow: hidden; text-overflow: ellipsis; white-space: nowrap;'}, (record.customerInfo.toString()).slice(0, 15))
            ]);
          }
        },
        // {
        //   prop: 'includeCustomerType',
        //   label: '包含客户类型',
        //   align:'center',
        //   minWidth: '120',
        // },
        {
          prop: 'orderType',
          label: '订单类型',
          align: 'left',
          minWidth: '120',
          render: (h, text) => {
            let show = "";
            this.dict.type.order_type.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'effectiveDate',
          label: '价目生效日期',
          align: 'left',
          minWidth: '140',
          render: (h, text) => {
            if (!text) return ''
            const dayjsData = dayjs(text)
            if (dayjsData.isValid() && dayjsData.isAfter(dayjs('1900'), 'year')) {
              return dayjsData.format('YYYY-MM-DD')
            }
            return text
          }
        },
        {
          prop: 'expireDate',
          label: '价目失效日期',
          align: 'left',
          minWidth: '140',
          render: (h, text) => {
            if (!text) return ''
            const dayjsData = dayjs(text)
            if (dayjsData.isValid() && dayjsData.isAfter(dayjs('1900'), 'year')) {
              return dayjsData.format('YYYY-MM-DD'); // format('YYYY-MM-DD HH:mm:ss')
            }
            return text
          }
        },
        {
          prop: 'sellerName',
          label: '销售组织',
          minWidth: '180',
          align: 'left',
          showOverflowTooltip: true
        },
        {
          prop: 'sort',
          label: '排序编号',
          minWidth: '100',
          align: 'left',
        },
        {
          prop: 'businessUserList',
          label: '业务人员',
          minWidth: '180',
          align: 'left',
          showOverflowTooltip: true,
          render: (h, text) => {
            console.log('text=', text);
            if (!text) return '';
            if (text instanceof Array) {
              let list = text.map(item => item.nickName);
              return list.toString();
            }
            return text
          }
        },
        {
          label: '操作',
          width: '120',
          type: 'operator',
          align: 'left',
          fixed: 'right',
          operators: this.operatorsFunc()
        },
      ];
    },

    /**
     * 渲染功能列表
     * @param {*} h 
     */
    toolbarRnd(h){
      let list = [];
      if (checkPermi(['basic-data:erp-price:list:setting'])) {
        list.push(<el-button type="primary" icon="el-icon-plus" vOn:click={() => this.onAddCost()}>配置可用价目表</el-button>);
      }
      return list;
    },

    operatorsFunc() {
    let list = [];
    if (checkPermi(['basic-data:erp-price:list:update'])) {
      list.push({label: '修改', command: 'edit'});
    }
    
    return list;
   },

    /**
     * 标题渲染
     * @param {*} h 
     */
    titleRender(h) {
      return <div>
        <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
        <span style="display: inline-block; color: #333333; font-size: 16px;">ERP价目表</span>
      </div>;
    },

    /**
     * 搜索列表查询
     */
     searchListQuery() {
      this.$refs['queryTable'].submitQuery();
    },

    /**
     * 修改参数格式
     * @param {*} queryData 
     */
    transformQuery(queryData) {
      let transParams = {}
      for (let keyName in queryData) {
        if (queryData.hasOwnProperty(keyName)) {
          if (keyName === 'createTimeRange') {
            if(queryData['createTimeRange'] && queryData['createTimeRange'].length){
              const [start, end] =  queryData[keyName]
              transParams['startTime'] = dayjs(start).startOf('day').format("YYYY-MM-DD HH:mm:ss")
              transParams['endTime'] = dayjs(end).endOf('day').format("YYYY-MM-DD HH:mm:ss")
            }
          } else {
            transParams[keyName] = queryData[keyName]
          }
        }
      }
      return transParams
    },

    /**
     * 操作页面
     * @param {*} command 
     * @param {*} record 
     */
    onOperator(command, record) {
      if('edit' === command){
        this.onPreviewInvoice(record)
      }
    },

    /**
     * 点击修改
     */
    onPreviewInvoice(row) {
      // console.log('row=', row);
      this.getUserInfoList(); // 获取业务人员列表
      this.curRecord = JSON.parse(JSON.stringify(row));
      // console.log('curRecord=', this.curRecord);
      if (this.curRecord.sort == null) {
        // console.log('进来了');
        this.curRecord.sort = undefined;
      }
      // this.$set(this.curRecord, 'num', undefined);
      let list = this.curRecord.businessUserList.map(item => item.nickName);
      if (!this.curRecord.hasOwnProperty('businessUserListStr')) {
        this.$set(this.curRecord, 'businessUserListStr', list.join('、'));
      } else {
        this.curRecord.businessUserListStr = list.join('、');
      }
      this.checkedConfigPersons = this.curRecord.businessUserList;
      this.orderTypeShow = true;
    },

    /**
     * 修改价目表对应订单类型的确定按钮
     */
    submitOrderTypeForm() {
      let params = {
        id : this.curRecord.id,
        orderType: this.curRecord.orderType, // 订单类型编码
        priceAlias: this.curRecord.priceAlias, // 价目表别名
        sort: this.curRecord.sort, // 排序
        businessUserIdList: this.curRecord.businessUserList.map(item => item.userId), // 关联业务人员id列表
      };
      // console.log('params=', params);
      this.$refs['updateForm'].validate(valid => {
        if (!valid) {
          this.saveloading = false;
          return;
        }
        this.btnOrderTypeLoad = true;
        settingPricesUpdate(params).then(res => {
          this.btnOrderTypeLoad = false;
          if (res.code === 200) {
            this.orderTypeShow = false;
            this.onRefreshTable();
            this.$modal.msgSuccess('修改成功！');
          } else {
            this.$modal.msgError('修改失败！');
          }
        }).catch(err => {
          this.btnOrderTypeLoad = false;
        });
      });

      // return;
      
    },

    /**
     * 获取业务人员列表
     */
    getUserInfoList() {
      getUserInfoList({}).then(res => {
        if (res.code == 200) {
          this.salesmans = res.data;
        }
      }).catch(err => {

      });
    },

    /**
     * 取消配置人员弹窗
     */
    cancelConfigPersonDialog() {
      this.configPersonShow = false;
    },

    /**
     * 显示配置人员弹窗
     */
    onConfigPerson() {
      this.filterPersonText = undefined;
      this.configPersonShow = true;
      this.checkedConfigPersons = JSON.parse(JSON.stringify(this.curRecord.businessUserList));
      this.$nextTick(()=>{
        this.$refs.menuPerson.setCheckedKeys([]);
      });
      if (this.checkedConfigPersons && this.checkedConfigPersons.length > 0) {
        this.checkedConfigPersons.forEach(item => {
          this.$nextTick(()=>{
            this.$refs.menuPerson.setChecked(item.userId, true ,true);
          });
        });
      }
    },

    /**
     * 配置业务人员确认按钮事件
     */
    submitFormConfigPerson() {
      this.curRecord.businessUserList = JSON.parse(JSON.stringify(this.checkedConfigPersons));
      let list = this.curRecord.businessUserList.map(item => item.nickName);
      if (!this.curRecord.hasOwnProperty('businessUserListStr')) {
        this.$set(this.curRecord, 'businessUserListStr', list.join('、'));
      } else {
        this.curRecord.businessUserListStr = list.join('、');
      }
      this.cancelConfigPersonDialog();
    },


    /**
     * 从列表中删除 删除已选中的配置业务人员
     * @param {*} row 
     */
     deleteCanPricePerson(row) {
      this.checkedConfigPersons.splice(this.checkedConfigPersons.indexOf(row), 1);
      this.$nextTick(()=>{
        this.$refs.menuPerson.setChecked(row.userId, false ,false);
      });
    },

    /**
     * 点击节点 配置业务人员
     * @param {*} item 
     * @param {*} node 
     * @param {*} v3 
     */
     nodeClickPerson(item, node, v3) {
      node.checked = !node.checked;
      if (node.checked == true) { // 选中
        this.checkedConfigPersons.push(item);
      } else { // 未选中
        this.checkedConfigPersons.splice(this.checkedConfigPersons.indexOf(item), 1);
      }
    },

    /**
     * 点击tree 配置业务人员
     * @param {*} item 
     * @param {*} de 
     */
     treeCheckPerson(item, data) {
      if (data.checkedKeys.indexOf(item.userId) !== -1) {
        this.checkedConfigPersons.push(item);
      } else {
        this.checkedConfigPersons.splice(this.checkedConfigPersons.indexOf(item), 1);
      }
     },


    /**
     * 取消 修改价目表对应订单类型的确定按钮
     */
    cancelOrderType() {
      this.orderTypeShow = false;
    },

    filterCustomerData(query, item) {
      return item.pinyin.indexOf(query) > -1;
    },
    /** 确认选择关联客户 */
    submitSelectCustomer() {
      this.editVisible = false;
    },

    /** 取消选择关联客户 */
    cancelSelectCustomer() {
      this.editVisible = false;
    },

    /**
     * 获取数据
     * @param {*} queryParams 
     */
    requestTableData(queryParams) {
      queryParams.effectiveDateBegin = undefined;
      queryParams.effectiveDateEnd = undefined;
      queryParams.expireDateBegin = undefined;
      queryParams.expireDateEnd = undefined;
      if (queryParams.effectiveTimeRange && queryParams.effectiveTimeRange.length == 2) {
        queryParams.effectiveDateBegin = queryParams.effectiveTimeRange[0];
        queryParams.effectiveDateEnd = queryParams.effectiveTimeRange[1];
      }
      if (queryParams.failureTimeRange && queryParams.failureTimeRange.length == 2) {
        queryParams.expireDateBegin = queryParams.failureTimeRange[0];
        queryParams.expireDateEnd = queryParams.failureTimeRange[1];
      }  

      return settingPricePages(queryParams).then(respData => {
        // console.log('respData=', respData);
        let list = respData.data.records;
        // console.log('list=', list);
        if (list) {
          list.forEach((item) => {
            // console.log('item=', item);
            let records = item.customerInfo ? item.customerInfo : [];
            let adds = [];

            records.forEach((item1) => {
              adds.push({name: item1});
            });
            item.customerInfos = adds;
            // item.customerInfo = adds;
          });
        }
        // console.log('list=', list);
        return {
          success: true,
          total: respData.data.total,
          data: list,
        }
      });
    },

    /**
     * 刷新列表
     */
    onRefreshTable(){
      this.$refs['queryTable'].refreshTable()
    },
    
    /**
     * 点击 配置可用价目表 按钮
     */
    onAddCost(){
      this.getSettingPrices().then(res => {
        let list = JSON.parse(JSON.stringify(this.settingSourcePrices));
        this.settingPriceList = []; //  所有可配置的价目表数据
        this.checkedSettingPrices = []; // 可用的价目表数据
        list && list.forEach((item) => {
          this.settingPriceList.push(item);
          if (item.useable == true) {
            this.checkedSettingPrices.push(item);
            this.$nextTick(()=>{
              this.$refs.menu.setChecked(item.id, true ,false);
            });
          }
        });
      });
      this.curRecord = {};
      this.editVisible = true;

      // let list = JSON.parse(JSON.stringify(this.settingSourcePrices));
      // this.settingPriceList = []; //  所有可配置的价目表数据
      // this.checkedSettingPrices = []; // 可用的价目表数据
      // list && list.forEach((item) => {
      //   this.settingPriceList.push(item);
      //   if (item.useable == true) {
      //     this.checkedSettingPrices.push(item);
      //     this.$nextTick(()=>{
      //       this.$refs.menu.setChecked(item.id, true ,false);
      //     });
      //   }
      // });
      

      // this.$nextTick(()=>{
      //   this.checkedSettingPrices.forEach((item) => {
      //     this.$refs.menu.setChecked(item.id, true ,false);
      //   });
      // });
    },

    /**
     * 过滤属性结构的数据
     * @param {*} value 
     * @param {*} data 
     */
     filterNodeArea(value, data) {
      if (!value) {
        return true;
      }
      return data.name.indexOf(value) !== -1;
    },

    /**
     * 过滤数据行结果的数据 业务人员列表
     * @param {*} value 
     * @param {*} data 
     */
    filterNodePerson(value, data) {
      if (!value) {
        return true;
      }
      return data.userDeptName.indexOf(value) !== -1;
    },

    /**
     * 从列表中删除 删除可用价格
     * @param {*} row 
     */
     deleteCanPrice(row) {
      this.checkedSettingPrices.splice(this.checkedSettingPrices.indexOf(row), 1);
      this.$nextTick(()=>{
        this.$refs.menu.setChecked(row.id, false ,false);
      });
    },

    /**
     * 点击节点 配置可用价目表
     * @param {*} item 
     * @param {*} node 
     * @param {*} v3 
     */
     nodeClick(item, node, v3) {
      node.checked = !node.checked;
      if (node.checked == true) { // 选中
        this.checkedSettingPrices.push(item);
      } else { // 未选中
        this.checkedSettingPrices.splice(this.checkedSettingPrices.indexOf(item), 1);
      }
    },

    /**
     * 点击tree 配置可用价目表
     * @param {*} item 
     * @param {*} de 
     */
     treeCheck(item, data) {
      if (data.checkedKeys.indexOf(item.id) !== -1) {
        this.checkedSettingPrices.push(item);
      } else {
        this.checkedSettingPrices.splice(this.checkedSettingPrices.indexOf(item), 1);
      }
     },

     /**
      * 选择配置可用价目表 点击确认
      */
     submitForm() {
      this.btnLoad = true;
      
      let useList = [];
      let params = {checkedPriceIds: useList};
      this.checkedSettingPrices.forEach((item) => {
        useList.push(item.id);
      });
      // console.log('params=', params);
      settingPriceStatus(params).then(res => {
        // console.log('res=', res);
        this.btnLoad = false;
        if (res.code === 200) {
          this.editVisible = false;
          this.onRefreshTable();
          this.getSettingPrices();
        }
      }).catch(err => {
        this.btnLoad = false;
      });
     },

     /**
      * 取消 选择配置可用价目表 弹窗
      */
     cancelDialog() {
      this.editVisible = false;
     },

    /**
     * 获取配置价目表
     */
    getSettingPrices() {
      return settingPrices({}).then(res => {
        if (res.code === 200) {
          const list = res.data;
          this.settingSourcePrices = [];
          list && list.forEach((item) => {
            item.name = item.priceCode + '-' + item.priceName + '-' + item.statusName;
            item.children = [];
            this.settingSourcePrices.push(item);
          });
        }
      });

      
    }



  }
}
</script>


<style lang="scss" scoped>
.dialog-main {
  display: flex;
  flex-direction: row;

  .dialog-left {
    flex: 1;
    // background-color: red;
    display: flex;
    flex-direction: column;
    .left-area {
      display: inline-block;
      width: 330px;
      // width:100%;
      height: 300px;
      margin-top: 5px;
      border: 1px solid #e5e6e7;
      background: #FFFFFF none;
      border-radius:4px;
      overflow: auto;
    }
  }
  .dialog-right {
    flex: 1;
    // background-color: orange;
    .right-top {
      margin-top: 8px;
      margin-bottom: 24px;
      display: inline-block;
    }
    ::v-deep.el-table__header-wrapper {
      border: 0;
      height:0;
    }
    ::v-deep.el-table__cell {
      border: 0;
    }
    
    ::v-deep.el-table .cell {
      line-height: 28.5px;
    }
    .right-bottom {
      height: 312px;
      overflow: auto;
      // background-color: lightcoral;
      .table-column-area {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        flex
        .table-column-area-span {
          // flex: 3;
          height: 28.5px;
          font-size: 14px;
          font-weight: 400;
        }
        
        .table-column-area-btn {
          // flex: 1;
        }
      }
    }
  }
}
</style>